<template>
    <div>        <Table 
            ref="tableRef" 
            :column="tableColumn" 
            :data="state.table.data" 
            :pagination="pagination" 
            v-model:showComSearch="showComSearchValue"
            :tableButtons="tableButtons"
            @selection-change="handleSelectionChange"
            v-loading="state.table.loading"
            :row-class-name="rowClassName"
            :row-key="(row: any) => row.id"
            :border="true"
            :stripe="true"
            :highlight-current-row="true"
            :header-cell-style="{background:'#f8f8f9', color: '#606266'}"
        >
            <!-- 搜索区域 -->
            <template v-slot:tableSearch>
                <div class="search-container">
                    <div class="search-item-group">
                        <div class="search-item">
                            <span class="search-label">{{ t('user.name') }}:</span>
                            <el-input
                                class="search-input"
                                v-model="state.form.search.userName"
                                :placeholder="t('user.pleaseEnterName')"
                                clearable
                                @keyup.enter="handleSearch"
                            >
                                <template #prefix>
                                    <Icon name="fa fa-user" />
                                </template>
                            </el-input>
                        </div>
                        
                        <div class="search-item">
                            <span class="search-label">{{ t('user.dept') }}:</span>
                            <el-input
                                class="search-input"
                                v-model="state.form.search.dept"
                                :placeholder="t('user.pleaseEnterDept')"
                                clearable
                                @keyup.enter="handleSearch"
                            >
                                <template #prefix>
                                    <Icon name="fa fa-building" />
                                </template>
                            </el-input>
                        </div>
                        
                        <div class="search-item">
                            <span class="search-label">{{ t('user.status') }}:</span>
                            <el-select
                                v-model="state.form.search.status"
                                :placeholder="t('user.pleaseSelect')"
                                clearable
                                class="search-input"
                            >
                                <el-option :label="t('user.enabled')" :value="1">
                                    <div class="option-with-icon">
                                        <Icon name="fa fa-check-circle" class="icon-success" />
                                        <span>{{ t('user.enabled') }}</span>
                                    </div>
                                </el-option>
                                <el-option :label="t('user.disabled')" :value="0">
                                    <div class="option-with-icon">
                                        <Icon name="fa fa-ban" class="icon-danger" />
                                        <span>{{ t('user.disabled') }}</span>
                                    </div>
                                </el-option>
                            </el-select>
                        </div>
                    </div>
                    
                    <div class="search-buttons">
                        <el-button type="primary" @click="handleSearch" :icon="'el-icon-Search'">
                            {{ t('user.search') }}
                        </el-button>
                        <el-button @click="handleReset" :icon="'el-icon-Delete'">
                            {{ t('user.reset') }}
                        </el-button>
                    </div>
                </div>
            </template>

            <!-- 批量操作 -->
            <template v-slot:batchActions>
                <el-dropdown @command="handleBatchCommand">
                    <el-button type="info" size="small">
                        {{ t('user.batchOperation') }} <Icon name="el-icon-ArrowDown" class="el-icon--right" />
                    </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="enable">{{ t('user.batchEnable') }}</el-dropdown-item>
                            <el-dropdown-item command="disable">{{ t('user.batchDisable') }}</el-dropdown-item>
                            <el-dropdown-item command="delete" divided>{{ t('user.batchDelete') }}</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
                <el-button size="small" type="warning" @click="clearSelection">{{ t('user.cancel') }}</el-button>
            </template>
            
            <!-- 头像列 -->
            <template v-slot:slotAvatar="{ data }">
                <el-avatar :size="40" :src="data.row.avatar || ''" :fit="'cover'" />
            </template>
            
            <!-- 状态列 -->
            <template v-slot:slotStatus="{ data }">
                <div class="status-column">
                    <el-switch
                        :loading="data.row.loading"
                        :model-value="parseInt(data.row.is_Enable) === 1"
                        @change="(val: boolean) => changeUserStatus(val, data.row)"
                        :active-color="'#13ce66'"
                        :inactive-color="'#ff4949'"
                        :disabled="isCurrentUser(data.row)"
                    />
                    <div class="status-tags">
                        <el-tag v-if="parseInt(data.row.is_Enable) === 1" type="success" size="small">{{ t('user.enabled') }}</el-tag>
                        <el-tag v-else type="info" size="small">{{ t('user.disabled') }}</el-tag>
                        <el-tag v-if="isCurrentUser(data.row)" type="warning" size="small" class="ml-2">{{ t('user.currentUser') }}</el-tag>
                    </div>
                </div>
            </template>
            
            <!-- 操作列 -->
            <template v-slot:slotOperation="{ data }">
                <el-button type="primary" link @click="handleEdit(data.row)">
                    <Icon name="fa fa-edit" /> {{ t('user.edit') }}
                </el-button>
                <el-button type="success" link @click="handleAssignRoles(data.row)">
                    <Icon name="fa fa-user-tag" /> {{ t('user.roles') }}
                </el-button>
                <el-button 
                    type="danger" 
                    link 
                    @click="handleDelete(data.row)"
                    :disabled="isCurrentUser(data.row)"
                    v-if="!isCurrentUser(data.row)">
                    <Icon name="fa fa-trash" /> {{ t('user.delete') }}
                </el-button>
                <el-tooltip 
                    v-else 
                    effect="dark" 
                    :content="t('user.cannotDeleteCurrentUser')" 
                    placement="top">
                    <el-button 
                        type="danger" 
                        link 
                        disabled>
                        <Icon name="fa fa-trash" /> {{ t('user.delete') }}
                    </el-button>
                </el-tooltip>
            </template>
        </Table>

        <!-- 用户表单对话框 -->
        <FormDialog v-if="state.form.operate !== ''" ref="formDialogRef" />
        
        <!-- 角色分配对话框 -->
        <RoleDialog ref="roleDialogRef" />
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, provide, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import userApi from '/@/api/backendManage/auth/user'
import { useAdminInfo } from '/@/stores/adminInfo'
import FormDialog from './form.vue'
import RoleDialog from './roleDialog.vue'
import Table from '/@/components/table/index.vue'

defineOptions({
    name: 'UserUser',
})

const { t } = useI18n()
const formDialogRef = ref()
const roleDialogRef = ref()
const tableRef = ref()
const adminInfo = useAdminInfo()

// 使用预定义的API接口
// userApi已从'/@/api/backendManage/auth/user'导入

// 控制表格公共搜索显示
const showComSearchValue = ref(true)

// 状态管理
const state = reactive({
    table: {
        loading: false,
        data: [],
    },
    form: {
        operate: '',
        search: {
            userName: '',
            dept: '',
            status: '' as string | number,
        },
        items: {} as Record<string, any>,
    },
    selection: [] as any[]
})

// 为子组件提供状态
provide('baTable', { state })

// 处理页码变更
const handleCurrentChange = (page: number) => {
    pagination.currentPage = page
    loadData()
}

// 处理每页条数变更
const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    pagination.currentPage = 1
    loadData()
}

// 搜索
const handleSearch = () => {
    pagination.currentPage = 1
    loadData()
}

// 重置搜索
const handleReset = () => {
    state.form.search.userName = ''
    state.form.search.dept = ''
    state.form.search.status = ''
    pagination.currentPage = 1
    loadData()
}

// 清除选择
const clearSelection = () => {
    if (tableRef.value) {
        tableRef.value.clearSelection()
    }
}

// 新增用户
function handleAdd() {
    state.form.operate = 'add'
    state.form.items = {}
    
    nextTick(() => {
        formDialogRef.value?.open('add')
    })
}
// 查询条件
const queryWhere = () =>{
        return {
            userName: state.form.search.userName || '',
            dept: state.form.search.dept || '',
            isEnable: state.form.search.status !== '' ? state.form.search.status : undefined
        }
}

// 加载表格数据
const loadData = () => {
    state.table.loading = true
    var query = queryWhere();
    userApi.getUserList({
        ...query,
        limit: pagination.pageSize,
        page: pagination.currentPage,
        orderBy: 'id',
        order: 'descending'
    })
    .then((res) => {
        if (res.data) {
            debugger
            state.table.data = res.data.dataList || []
            pagination.total = res.data.totalCount || 0
        }
    })
    .finally(() => {
        state.table.loading = false
    })
}

// 导出数据
const handleExport = () => {
    state.table.loading = true;
    var query = queryWhere();
    userApi.getUserList({
         ...query,
        limit: 1000, // 导出最多1000条
        page: 1,
    })
    .then((res) => {
        if (res.data && res.data.dataList) {
            exportToExcel(res.data.dataList)
        } else {
            ElMessage.warning(t('user.noDataToExport'))
        }
    })
    .finally(() => {
        state.table.loading = false
    })
}

// 表格按钮
const tableButtons = reactive([
    {
        tipName: t('user.addUser'),
        iconName: "el-icon-Plus",
        name: t('user.add'),
        onClick: handleAdd
    },
    {
        tipName: t('user.exportData'),
        iconName: "el-icon-Download",
        name: t('user.export'),
        onClick: handleExport
    },
    {
        tipName: t('user.refreshData'),
        iconName: "el-icon-Refresh",
        name: t('user.refresh'),
        onClick: loadData
    }
])

// 分页配置
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
    layout: "total, sizes, prev, pager, next, jumper",
    pageSizes: [10, 20, 50, 100],
    onTableSizeChange: handleSizeChange,
    onTableCurrentChange: handleCurrentChange,
    onTableChange: (currentPage: number, pageSize: number) => {
        console.log('tableChange', currentPage, pageSize);
    }
})

// 表格列配置
const tableColumn = reactive<TableColumn[]>([
    { 
        prop: 'id', 
        label: 'ID', 
        show: true,
        width: '80',
        sortable: true,
    },
    { 
        prop: 'avatar', 
        label: t('user.avatar'), 
        show: true,
        width: '80',
        slotName: 'slotAvatar',
    },
    { 
        prop: 'login_Name', 
        label: t('user.loginName'), 
        show: true,
        sortable: true,
        fieldType: 'text',
    },
    { 
        prop: 'name', 
        label: t('user.name'), 
        show: true,
        fieldType: 'text',
    },
    { 
        prop: 'dept', 
        label: t('user.dept'), 
        show: true,
        fieldType: 'text', 
    },
    { 
        prop: 'email', 
        label: t('user.email'), 
        show: true,
        fieldType: 'text',
        showOverflowTooltip: true,
        width: '180',
    },
    { 
        prop: 'phone', 
        label: t('user.phone'), 
        show: true,
        fieldType: 'text', 
    },
    { 
        prop: 'company', 
        label: t('user.company'), 
        show: true,
        fieldType: 'text', 
    },
    { 
        prop: 'last_Login_Time', 
        label: t('user.lastLoginTime'), 
        show: true,
        width: '180',
        sortable: true,
        fieldType: 'datetime',
    },
    { 
        prop: 'is_Enable', 
        label: t('user.status'), 
        show: true,
        slotName: 'slotStatus',
        fieldType: 'select',
        fieldConfig: {
            options: [
                { label: t('user.enabled'), value: 1 },
                { label: t('user.disabled'), value: 0 }
            ]
        }
    },
    { 
        prop: 'operation', 
        label: t('user.operation'), 
        show: true,
        slotName: 'slotOperation',
        width: '280',
        fixed: 'right',
    }
])

// 导出到Excel
const exportToExcel = (data: any[]) => {
    import('xlsx').then(xlsx => {
        // 准备导出数据
        const exportData = data.map(item => {
            return {
                'ID': item.id,
                [t('user.loginName')]: item.login_Name,
                [t('user.name')]: item.name,
                [t('user.dept')]: item.dept,
                [t('user.email')]: item.email,
                [t('user.phone')]: item.phone,
                [t('user.company')]: item.company,
                [t('user.status')]: parseInt(item.is_Enable) === 1 ? t('user.enabled') : t('user.disabled'),
                [t('user.lastLoginTime')]: item.last_Login_Time || '-'
            }
        });
        
        // 创建工作簿和工作表
        const worksheet = xlsx.utils.json_to_sheet(exportData);
        const workbook = xlsx.utils.book_new();
        xlsx.utils.book_append_sheet(workbook, worksheet, 'Users');
        
        // 导出文件
        const date = new Date();
        const fileName = `users_${date.getFullYear()}${(date.getMonth() + 1).toString().padStart(2, '0')}${date.getDate().toString().padStart(2, '0')}.xlsx`;
        xlsx.writeFile(workbook, fileName);
        ElMessage.success(t('user.exportSuccess'));
    }).catch(() => {
        ElMessage.error(t('user.exportFailed'));
    });
}

// 修改用户状态
const changeUserStatus = (status: boolean, row: Record<string, any>) => {
    // 检查是否是当前登录用户
    if (isCurrentUser(row)) {
        ElMessage.warning(t('user.cannotModifyCurrentUser'))
        return
    }
    
    row.loading = true
    userApi.enableUser(row.id, status)
        .finally(() => {
            row.loading = false
            loadData()
        })
}

// 批量操作
const handleBatchCommand = (command: string) => {
    if (state.selection.length === 0) {
        ElMessage.warning(t('user.pleaseSelectUsers'))
        return
    }
    
    let confirmMessage = ''
    // 过滤掉当前登录用户
    const filteredSelection = state.selection.filter(item => !isCurrentUser(item))
    
    if (filteredSelection.length === 0) {
        ElMessage.warning(t('user.cannotOperateCurrentUser'))
        return
    }
    
    // 如果有被过滤的用户，显示提示信息
    if (filteredSelection.length < state.selection.length) {
        ElMessage.info(t('user.currentUserSkipped'))
    }
    
    const ids = filteredSelection.map(item => item.id)
    
    switch (command) {
        case 'enable':
            confirmMessage = t('user.confirmBatchEnable')
            ElMessageBox.confirm(confirmMessage, t('user.tip'), {
                type: 'warning',
                confirmButtonText: t('user.confirm'),
                cancelButtonText: t('user.cancel')
            }).then(() => {
                userApi.batchEnableUsers(ids, true)
                    .then(() => {
                        loadData()
                        if (tableRef.value) {
                            tableRef.value.clearSelection()
                        }
                    })
            })
            break
            
        case 'disable':
            confirmMessage = t('user.confirmBatchDisable')
            ElMessageBox.confirm(confirmMessage, t('user.tip'), {
                type: 'warning',
                confirmButtonText: t('user.confirm'),
                cancelButtonText: t('user.cancel')
            }).then(() => {
                userApi.batchEnableUsers(ids, false)
                    .then(() => {
                        loadData()
                        if (tableRef.value) {
                            tableRef.value.clearSelection()
                        }
                    })
            })
            break
            
        case 'delete':
            confirmMessage = t('user.confirmBatchDelete')
            ElMessageBox.confirm(confirmMessage, t('user.tip'), {
                type: 'warning',
                confirmButtonText: t('user.confirm'),
                cancelButtonText: t('user.cancel')
            }).then(() => {
                userApi.batchDeleteUsers(ids)
                    .then(() => {
                        loadData()
                        if (tableRef.value) {
                            tableRef.value.clearSelection()
                        }
                    })
            })
            break
    }
}

// 删除用户
const handleDelete = (row: Record<string, any>) => {
    // 检查是否是当前登录用户
    if (isCurrentUser(row)) {
        ElMessage.warning(t('user.cannotDeleteCurrentUser'))
        return
    }
    
    ElMessageBox.confirm(t('user.confirmDelete'), t('user.tip'), {
        type: 'warning',
        confirmButtonText: t('user.confirm'),
        cancelButtonText: t('user.cancel')
    }).then(() => {
        userApi.deleteUser(row.id)
            .then(() => {
                loadData()
            })
    })
}

// 判断是否为当前登录用户
const isCurrentUser = (row: Record<string, any>) => {
    // 确保与管理员ID进行比较时都转换为相同类型
    return parseInt(row.id) === parseInt(adminInfo.id)
}

// 表格多选变化时的回调
const handleSelectionChange = (selection: any[]) => {
    // 过滤掉当前登录用户，不允许选择当前用户
    const filteredSelection = selection.filter(item => !isCurrentUser(item))
    
    // 如果有被过滤的项目，说明当前用户被选中了，需要给出提示
    if (filteredSelection.length < selection.length) {
        // 轻提示，不打断用户操作
        ElMessage.info({
            message: t('user.cannotOperateCurrentUser'),
            duration: 2000,
            showClose: true,
            offset: 80
        })
    }
    
    state.selection = filteredSelection
}

// 编辑用户
const handleEdit = (row: Record<string, any>) => {
    state.form.operate = 'edit'
    state.form.items = { ...row }
    
    nextTick(() => {
        formDialogRef.value?.open('edit')
    })
}

// 分配角色
const handleAssignRoles = (row: Record<string, any>) => {
    roleDialogRef.value?.open(row.id, row.name)
}

// 监听更新事件，用于表单提交或角色分配后刷新数据
const handleUpdate = () => {
    loadData()
}

// 为行添加自定义类名
const rowClassName = ({ row }: { row: Record<string, any> }) => {
    return isCurrentUser(row) ? 'current-user-row' : ''
}

// 组件挂载后加载数据
onMounted(() => {
    loadData()
    window.addEventListener('update', handleUpdate)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
    window.removeEventListener('update', handleUpdate)
})
</script>

<style lang="scss" scoped>
/* 搜索区域样式 */
.search-container {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 16px;
    padding: 8px 0;
    .search-item-group {
        display: flex;
        flex-wrap: wrap;
        flex: 1;
        gap: 16px;
        
        .search-item {
            display: flex;
            align-items: center;
            
            .search-label {
                margin-right: 8px;
                white-space: nowrap;
                color: var(--el-text-color-regular);
                font-weight: 500;
            }
            
            .search-input {
                width: 220px;
            }
        }
    }
    
    .search-buttons {
        display: flex;
        gap: 8px;
        
        .el-button {
            padding: 8px 20px;
        }
    }
}

/* 下拉选项样式 */
:deep(.option-with-icon) {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .icon-success {
        color: var(--el-color-success);
    }
    
    .icon-danger {
        color: var(--el-color-danger);
    }
}

/* 状态列样式 */
.status-column {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .el-switch {
        margin-right: 8px;
    }
    
    .status-tags {
        display: flex;
        align-items: center;
        gap: 4px;
    }
}

/* 当前用户行样式 */
.current-user-row {
    background-color: rgba(var(--el-color-primary-rgb), 0.1) !important;
    font-weight: bold;
    
    td {
        border-bottom-color: rgba(var(--el-color-primary-rgb), 0.2) !important;
    }
    
    &:hover > td {
        background-color: rgba(var(--el-color-primary-rgb), 0.15) !important;
    }
}

/* 响应式布局 */
@media (max-width: 768px) {
    .search-container {
        flex-direction: column;
        align-items: flex-start;
        
        .search-item-group {
            width: 100%;
            
            .search-item {
                width: 100%;
                
                .search-input {
                    width: 100%;
                }
            }
        }
        
        .search-buttons {
            width: 100%;
            justify-content: flex-end;
            margin-top: 16px;
        }
    }
}
</style>
